/**
 * Project Name:wxcy-app
 * File Name:LogisticsUtils.java
 * Package Name:cn.bluemobi.app.utils
 * Date:2016年10月28日上午9:52:25
 * Copyright (c) 2016, bluemobi.cn All Rights Reserved.
 *
 */

package cn.bluemobi.app.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import cn.bluemobi.app.core.utils.PropertiesUtils;

/**
 * 
 * @author lvxh
 * 
 */
public class LogisticsUtils {
    public static final String DEF_CHATSET = "UTF-8";

    public static final int DEF_CONN_TIMEOUT = 30000;

    public static final int DEF_READ_TIMEOUT = 30000;

    public static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";

    // 配置您申请的KEY
    public static final String APPKEY = PropertiesUtils.getProperty("LOGISTICS_KEY");

    // 1.常用快递查询API
    public static Map<String, Object> findLogisticsDetail(String logisticsCode, String logisticsNumber) {
        String result = null;
        String url = "http://v.juhe.cn/exp/index";// 请求接口地址
        Map<String, Object> params = new HashMap<String, Object>();// 请求参数
        params.put("com", logisticsCode);// 需要查询的快递公司编号
        params.put("no", logisticsNumber);// 需要查询的订单号
        params.put("key", APPKEY);// 应用APPKEY(应用详细页查询)
        params.put("dtype", "json");// 返回数据的格式,xml或json，默认json
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            result = net(url, params, "GET");
            // map = JsonUtils.jsonStr2Map(result);
            // JSONObject object = JSONObject.fromObject(result);
            map = logisticsInfo(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    @SuppressWarnings("unchecked")
    private static Map<String, Object> logisticsInfo(String jsonStr) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> map = JsonUtils.jsonStr2Map(jsonStr);
        if (StringUtils.equals(map.get("error_code").toString(), "0")) {
            Map<String, Object> logisticsMap = new HashMap<String, Object>();
            Map<String, Object> result = (Map<String, Object>) map.get("result");
            logisticsMap.put("company", result.get("company"));
            logisticsMap.put("no", result.get("no"));
            logisticsMap.put("com", result.get("com"));
            List<Map<String, Object>> list = (List<Map<String, Object>>) result.get("list");
            Collections.reverse(list);
            logisticsMap.put("logisticsInfoList", list);
            resultMap.put("reason", map.get("reason"));
            resultMap.put("result", "0");
            resultMap.put("logisticsMap", logisticsMap);
        } else {
            resultMap.put("reason", map.get("reason"));
            resultMap.put("result", "-1");
        }
        return resultMap;
    }

    // 2.快递公司编号对照表
    public static Map<String, Object> getRequest2() {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String result = null;
        String url = "http://v.juhe.cn/exp/com";// 请求接口地址
        Map<String, Object> params = new HashMap<String, Object>();// 请求参数
        params.put("key", APPKEY);
        try {
            result = net(url, params, "GET");
            resultMap = JsonUtils.jsonStr2Map(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    /**
     * 
     * @param strUrl 请求地址
     * @param params 请求参数
     * @param method 请求方法
     * @return 网络请求字符串
     * @throws Exception
     */
    public static String net(String strUrl, Map<String, Object> params, String method) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if (method == null || method.equals("GET")) {
                strUrl = strUrl + "?" + urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if (method == null || method.equals("GET")) {
                conn.setRequestMethod("GET");
            } else {
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params != null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }

    // 将map型转为请求参数型
    public static String urlencode(Map<String, Object> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    // { \
    // "resultcode\":\"201\", \"reason\":\"参数错误：快递公司编号错误\", \"result\":null,
    // \"error_code\":204301 }

    public static void main(String[] args) {
        // String json =
        // "{ \"resultcode\":\"201\", \"reason\":\"参数错误：快递公司编号错误\",  \"result\":null, \"error_code\":204301  }";
        String json = " {  \"resultcode\":\"200\", \"reason\":\"查询成功\",  \"result\":{\"company\":\"中通\",\"com\":\"zto\",\"no\":\"778892427500\",\"status\":\"1\", \"list\":[{\"datetime\":\"2017-03-18 01:23:19\",\"remark\":\"[广州市][荔湾和平]的中信彭紫茵已收件 电话:13268112720\",\"zone\":\"\"} ]}, \"error_code\":0 }";
        Map<String, Object> map = logisticsInfo(json);
        System.out.println(map.toString());

    }
}
